package com.whc.gulimall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.utils.PageUtils;
import com.whc.common.utils.Query;
import com.whc.common.utils.R;
import com.whc.gulimall.product.dao.SkuInfoDao;
import com.whc.gulimall.product.dto.SecKillSkuDTO;
import com.whc.gulimall.product.entity.SkuInfoEntity;
import com.whc.gulimall.product.feign.SeckillFeignService;
import com.whc.gulimall.product.service.*;
import com.whc.gulimall.product.vo.SkuItemVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


/**
 * @author angaoen
 */
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    /**
     * sku图片 Service
     */
    @Resource
    private SkuImagesService skuImagesService;

    /**
     * spu信息介绍
     */
    @Resource
    private SpuInfoDescService spuInfoDescService;

    /**
     * 属性分组
     */
    @Resource
    private AttrGroupService attrGroupService;

    /**
     * sku销售属性&值
     */
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private SeckillFeignService seckillFeignService;

    /**
     * ThreadPoolExecutor
     */
    @Resource
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StrUtil.isNotBlank(key)) {
            queryWrapper.and(w -> w.eq("sku_id", key).or().like("sku_name", key));
        }

        String catelogId = (String) params.get("catelogId");
        if (StrUtil.isNotBlank(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StrUtil.isNotBlank(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (StrUtil.isNotBlank(min)) {
            BigDecimal bigDecimalMin = new BigDecimal(min);
            if (bigDecimalMin.compareTo(BigDecimal.ZERO) > 0) {
                queryWrapper.ge("price", bigDecimalMin);
            }
        }
        String max = (String) params.get("max");
        if (StrUtil.isNotBlank(max)) {
            BigDecimal bigDecimalMax = new BigDecimal(max);
            if (bigDecimalMax.compareTo(BigDecimal.ZERO) > 0) {
                queryWrapper.le("price", bigDecimalMax);
            }
        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 通过skuId获取到skuName
     *
     * @param skuIds skuId列表
     * @return map列表
     */
    @Override
    public Map<Long, String> listSkuNamesBySkuIds(List<Long> skuIds) {
        if (CollUtil.isNotEmpty(skuIds)) {
            List<SkuInfoEntity> skuInfoEntities = baseMapper
                    .selectList(new QueryWrapper<SkuInfoEntity>().in("sku_id", skuIds));
            if (CollUtil.isNotEmpty(skuInfoEntities)) {
                return skuInfoEntities.stream()
                        .collect(Collectors.toMap(SkuInfoEntity::getSkuId, SkuInfoEntity::getSkuName));
            }
        }
        return null;
    }

    /**
     * 根据spuId获取到sku列表
     *
     * @param spuId spuId
     * @return sku列表
     */
    @Override
    public List<SkuInfoEntity> listBySpuId(Long spuId) {
        return baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    /**
     * 展示当前sku的详情
     *
     * @param skuId skuId
     * @return SkuItemVo
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        // 发送异步请求
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = getById(skuId);
            skuItemVo.setSkuInfoEntity(skuInfoEntity);
            return skuInfoEntity;
        });

        // 开启新线程获取spu的销售性组合
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(item ->
                skuItemVo.setSaleAttr(skuSaleAttrValueService.listSaleAttrValueBySpuId(item.getSpuId())), executor);

        // 开启新线程获取spu的介绍
        CompletableFuture<Void> despFuture = infoFuture.thenAcceptAsync(item ->
                skuItemVo.setDesp(spuInfoDescService.getById(item.getSpuId())), executor);

        // 开启新线程获取spu的规格参数信息
        CompletableFuture<Void> attrGroupFuture = infoFuture.thenAcceptAsync(item ->
                skuItemVo.setAttrGroup(attrGroupService
                        .listAttrGroupByCatelogAndSpuId(item.getCatalogId(), item.getSpuId())), executor);

        // 开启一个新的线程执行任务
        // sku的图片信息
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() ->
                skuItemVo.setImages(skuImagesService.listSkuImagesBySkuId(skuId)), executor);

        // 开启新线程获取商品的秒杀信息
        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuInfoBySkuId(skuId);
            if (Objects.equals(0, r.getCode())) {
                skuItemVo.setSecKillSkuDTO(r.getData(new TypeReference<SecKillSkuDTO>() {
                }));
            }
        }, executor);

        // 阻塞等待所有业务逻辑完成
        CompletableFuture.allOf(saleAttrFuture, despFuture, attrGroupFuture, imagesFuture, secKillFuture).get();

        return skuItemVo;
    }

    /**
     * 通过skuId列表获取到最新价格
     *
     * @param skuIds skuIds
     * @return KV键值对，K为skuId，V为最新商品价格
     */
    @Override
    public Map<Long, BigDecimal> listSkuPricesByIds(List<Long> skuIds) {
        List<SkuInfoEntity> skuInfoEntities = this.listByIds(skuIds);
        return CollUtil.isNotEmpty(skuInfoEntities)
                ? skuInfoEntities.stream().collect(Collectors.toMap(SkuInfoEntity::getSkuId, SkuInfoEntity::getPrice))
                : null;
    }
}

